<?php
namespace Components\Account\User;

class Filter extends \Phalcon\Filter implements \Phalcon\FilterInterface {
	private $data = [];
	private $errors = [];
	private $currentTime;

	public function setData($data) {
		$this -> currentTime = time();
		$this -> data = $data;
		return $this;
	}

	public function execute() {
		if(empty($this -> errors)) {
			return ['code'=>0,'data'=>$this->data];
		}

		return ['code'=>-1,'message'=>$this->errors[0]];
	}

	public function addPAccount() {
		if(isset($this -> data['p_account']) && !empty($this -> data['p_account'])) {
			$findFirst = Model::findFirst(['account = "' . $this -> data['p_account'] . '"']);
			if($findFirst) {
				$this -> data['pid'] = $findFirst -> user_id;
			} else {
				$this -> data['pid'] = 0;
			}
			unset($this -> data['p_account']);
		} else {
			$this -> data['pid'] = 0;
		}

		return $this;
	}

	public function addCellphone() {
		if(isset($this -> data['cellphone']) && !empty($this -> data['cellphone'])) {
			$this -> data['cellphone'] = $this -> sanitize($this -> data['cellphone'], ['string','trim']);
		}

		return $this;
	}

	public function addAccount() {
		if(isset($this -> data['account']) && !empty($this -> data['account'])) {
			$this -> data['account'] = $this -> sanitize($this -> data['account'], ['string','trim']);
		}

		return $this;
	}

	public function addPassword($di) {
		if(isset($this -> data['password']) && !empty($this -> data['password'])) {
			$this -> data['password'] = $di -> get('security') -> hash($this -> data['password']);
		}

		return $this;
	}

	public function addSafePassword($di) {
		if(isset($this -> data['safe_password']) && !empty($this -> data['safe_password'])) {
			$this -> data['safe_password'] = $di -> get('security') -> hash($this -> data['safe_password']);
		}

		return $this;
	}

	public function addLevel() {
		if(isset($this -> data['level']) && !empty($this -> data['level'])) {
			$this -> data['level'] = $this -> sanitize($this -> data['level'], 'int');
		}

		return $this;
	}

	public function addStatus() {
		if(isset($this -> data['status']) && !empty($this -> data['status'])) {
			$this -> data['status'] = $this -> sanitize($this -> data['status'], 'int');
		}

		return $this;
	}

	public function setCreateTime() {
		if(!isset($this -> data['create_time'])) {
			$this -> data['create_time'] = $this -> currentTime;
		}

		return $this;
	}

	public function setLastUpdateTime() {
		if(!isset($this -> data['last_update_time'])) {
			$this -> data['last_update_time'] = $this -> currentTime;
		}

		return $this;
	}
}
